package chapter18;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2019-03-31 21:21
 */
class House implements Serializable {

}

class Anmial implements Serializable {
    private String name;
    private House preferredHouse;

    public Anmial(String name, House preferredHouse) {
        this.name = name;
        this.preferredHouse = preferredHouse;
    }

    @Override
    public String toString() {
        return "Anmial{" +
                "name='" + name + '\'' +
                ", preferredHouse=" + preferredHouse +
                '}';
    }
}

public class MyWorld {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        House house = new House();
        List<Anmial> anmials = new ArrayList<>();
        anmials.add(new Anmial("Bosco the dog", house));
        anmials.add(new Anmial("Ralph the hamster", house));
        anmials.add(new Anmial("Molly the cat", house));
        System.out.println("anmials:" + anmials);
        ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(buf1);
        out.writeObject(anmials);
        out.writeObject(anmials);

        // write a different stream
        ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
        ObjectOutputStream out2 = new ObjectOutputStream(buf2);
        out2.writeObject(anmials);

        // now get them back
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray()));
        ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray()));

        List<Anmial> anmials1 = (List<Anmial>) in.readObject();
        List<Anmial> anmials2 = (List<Anmial>) in.readObject();
        List<Anmial> anmials3 = (List<Anmial>) in2.readObject();

        System.out.println("anmials1:" + anmials1);
        System.out.println("anmials2:" + anmials2);
        System.out.println("anmials3:" + anmials3);
    }
}
